/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.persistence.hibernate.core;

import com.blandware.atleap.common.util.PartialCollection;
import com.blandware.atleap.common.util.QueryInfo;
import com.blandware.atleap.common.util.StringUtil;
import com.blandware.atleap.model.core.ContentField;
import com.blandware.atleap.model.core.Localizable;
import com.blandware.atleap.persistence.core.ContentFieldDAO;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>Hibernate implementation of ContentFieldDAO</p>
 * <p><a href="ContentFieldDAOHibernate.java.html"><i>View Source</i></a></p>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.32 $ $Date: 2008/06/23 13:24:53 $
 */
public class ContentFieldDAOHibernate extends BaseDAOHibernate implements ContentFieldDAO {

	// ~ CRUD Methods ================================================================

	/**
	 * @see com.blandware.atleap.persistence.core.ContentFieldDAO#createContentField(com.blandware.atleap.model.core.ContentField, com.blandware.atleap.model.core.Localizable)
	 */
	public Long createContentField(ContentField contentField, Localizable localizable) {
		localizable.addContentField(contentField);
		return (Long) getHibernateTemplate().save(contentField);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.ContentFieldDAO#retrieveContentField(java.lang.Long)
	 */
	public ContentField retrieveContentField(Long contentFieldId) {
		return (ContentField) getHibernateTemplate().get(ContentField.class, contentFieldId);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.ContentFieldDAO#updateContentField(com.blandware.atleap.model.core.ContentField, com.blandware.atleap.model.core.Localizable)
	 */
	public void updateContentField(ContentField contentField, Localizable localizable) {
		ContentField oldContentField = localizable.updateContentField(contentField);
        removeFromCache(oldContentField);
		getHibernateTemplate().update(contentField);
	}

	/**
	 * @see com.blandware.atleap.persistence.core.ContentFieldDAO#deleteContentField(com.blandware.atleap.model.core.ContentField)
	 */
	public void deleteContentField(ContentField contentField) {
		getHibernateTemplate().delete(contentField);
		contentField.getOwner().removeContentField(contentField);
	}

	// ~ Additional methods ================================================================


	/**
	 * @see com.blandware.atleap.persistence.core.ContentFieldDAO#listContentFields(com.blandware.atleap.common.util.QueryInfo)
	 */
	public PartialCollection listContentFields(QueryInfo queryInfo) {
		String whereClause = new String();
		String orderByClause = new String();
		if ( queryInfo != null ) {
			whereClause = queryInfo.getWhereClause();
			orderByClause = queryInfo.getOrderByClause();
			if ( whereClause != null && whereClause.length() != 0 ) {
				whereClause = " and " + whereClause;
			} else {
				whereClause = new String();
			}
			if ( orderByClause != null && orderByClause.length() != 0 ) {
				orderByClause = " order by " + orderByClause;
			} else {
				orderByClause = new String();
			}
		}

		Long ownerId = null;
		if ( queryInfo != null ) {
			if ( queryInfo.getQueryParameters() != null ) {
				ownerId = (Long) queryInfo.getQueryParameters().get("ownerId");
			}
		}
		List list = null;
		Integer total = null;
		ArrayList args = new ArrayList();
		String hqlPart = new String();
		if ( ownerId != null ) {
			hqlPart = "from ContentField f where (f.owner.id = ?) and (f.internal = 'F')" + whereClause;
			args.add(ownerId);
		} else {
			hqlPart = "from ContentField f where (f.internal = 'T')" + whereClause;
		}
		if ( queryInfo != null && (queryInfo.getLimit() != null || queryInfo.getOffset() != null) ) {
			String hqlForTotal = "select count(f.id) " + hqlPart;
			total = findUniqueIntegerResult(hqlForTotal, args.toArray());
			if ( total == null ) {
				total = new Integer(0);
			}
		}
        // If we don't have any info about the total number of results yet or
        // we know that there's something that will be found, then fetch data
		if ( total == null || total.intValue() > 0 ) {
			String hql = "select f " + hqlPart + orderByClause;
			list = executeFind(hql, queryInfo, args.toArray());
			if ( total == null ) {
				total = new Integer(list.size());
			}
		} else {
			list = new ArrayList();
		}
		return new PartialCollection(list, total);

	}

	/**
	 * @see com.blandware.atleap.persistence.core.ContentFieldDAO#hasDuplicates(com.blandware.atleap.model.core.ContentField, Long)
	 */
	public boolean hasDuplicates(ContentField contentField, Long ownerId) {

		ArrayList args = new ArrayList();
		args.add(contentField.getIdentifier());
		args.add(ownerId);

		String hql = "select count(f.id) from ContentField f where f.identifier = ? and f.owner.id = ?";
		if ( contentField.getId() != null ) {
			hql += " and f.id != ?";
			args.add(contentField.getId());
		}

		int count = findUniqueIntegerResult(hql, args.toArray()).intValue();

		return count > 0;
	}

	// ~ Finders ================================================================

	/**
	 * @see com.blandware.atleap.persistence.core.ContentFieldDAO#findContentFieldByLayoutDefinition(java.lang.String, java.lang.String)
	 */
	public ContentField findContentFieldByLayoutDefinition(String identifier, String definition) {
		return (ContentField) findUniqueResult("select field from Layout layout inner join layout.contentFields field where layout.definition = ? and field.identifier = ?", new Object[]{definition, identifier});
	}

	/**
	 * @see com.blandware.atleap.persistence.core.ContentFieldDAO#findIndexedContentFieldsByLayoutDefinition(String, String) 
	 */
	public List findIndexedContentFieldsByLayoutDefinition(String identifier, String definition) {
        String hql = new StringBuffer("select distinct field from Layout layout inner join layout.contentFields field ")
                .append("where ")
                .append("field.identifier like '")
                .append(StringUtil.sqlEscape(identifier)).append("[%]' ")
                .append("and layout.definition = ? ")
                .toString();
		return executeFind(hql, new Object[]{definition});
	}

    /**
	 * @see com.blandware.atleap.persistence.core.ContentFieldDAO#findIndexedContentFieldsByLayoutDefinitionAndLocale(java.lang.String, java.lang.String, java.lang.String)
	 */
	public List findIndexedContentFieldsByLayoutDefinitionAndLocale(String identifier, String definition, String locale) {
        String hql = new StringBuffer("select distinct field from Layout layout inner join layout.contentFields field inner join field.contentFieldValues value ")
                .append("where ")
                .append("field.identifier like '")
                .append(StringUtil.sqlEscape(identifier)).append("[%]' ")
                .append("and layout.definition = ? ")
                .append("and (value.contentLocale.identifier = ? or value.contentLocale.defaultInstance = 'T')")
                .toString();
		return executeFind(hql, new Object[]{definition, locale});
	}

	/**
	 * @see com.blandware.atleap.persistence.core.ContentFieldDAO#findContentFieldByPageUri(java.lang.String, java.lang.String)
	 */
	public ContentField findContentFieldByPageUri(String identifier, String uri) {
        return (ContentField) findUniqueResult("select field from Page page inner join page.contentFields field where page.uri = ? and field.identifier = ?", new Object[]{uri, identifier});
	}

	/**
	 * @see com.blandware.atleap.persistence.core.ContentFieldDAO#findIndexedContentFieldsByPageUri(String, String)
	 */
	public List findIndexedContentFieldsByPageUri(String identifier, String uri) {
        String hql = new StringBuffer("select distinct field from Page page inner join page.contentFields field ")
                .append("where ").append("field.identifier like '")
                .append(StringUtil.sqlEscape(identifier)).append("[%]' ")
                .append("and page.uri = ? ")
                .toString();
		return executeFind(hql, new Object[]{uri});
	}

    /**
	 * @see com.blandware.atleap.persistence.core.ContentFieldDAO#findIndexedContentFieldsByPageUriAndLocale(java.lang.String, java.lang.String, java.lang.String)
	 */
	public List findIndexedContentFieldsByPageUriAndLocale(String identifier, String uri, String locale) {
        String hql = new StringBuffer("select distinct field from Page page inner join page.contentFields field inner join field.contentFieldValues value ")
                .append("where ").append("field.identifier like '")
                .append(StringUtil.sqlEscape(identifier)).append("[%]' ")
                .append("and page.uri = ? ")
                .append("and (value.contentLocale.identifier = ? or value.contentLocale.defaultInstance = 'T')")
                .toString();
		return executeFind(hql, new Object[]{uri, locale});
	}

	/**
	 * @see com.blandware.atleap.persistence.core.ContentFieldDAO#findContentFieldByLocalizable(java.lang.String, com.blandware.atleap.model.core.Localizable)
	 */
	public ContentField findContentFieldByLocalizable(String identifier, Localizable localizable) {
		return (ContentField) findUniqueResult("from ContentField f  where f.identifier = ? and f.owner = ?", new Object[]{identifier, localizable});
	}
}

